/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.worker.receiver;

import org.ourgrid.broker.actions.ErrorOcurredMessageHandle;
import org.ourgrid.broker.actions.HereIsGridProcessResultMessageHandle;
import org.ourgrid.common.executor.ExecutorException;
import org.ourgrid.common.executor.ExecutorHandle;
import org.ourgrid.common.executor.ExecutorResult;
import org.ourgrid.common.interfaces.Worker;
import org.ourgrid.common.interfaces.WorkerClient;
import org.ourgrid.common.interfaces.WorkerExecutionServiceClient;
import org.ourgrid.common.interfaces.management.RemoteWorkerManagementClient;
import org.ourgrid.common.interfaces.management.WorkerManagementClient;
import org.ourgrid.common.interfaces.to.GridProcessErrorTypes;
import org.ourgrid.reqtrace.Req;
import org.ourgrid.worker.WorkerConstants;
import org.ourgrid.worker.controller.ExecutionController;
import org.ourgrid.worker.controller.GridProcessError;
import org.ourgrid.worker.controller.WorkerController;
import org.ourgrid.worker.dao.WorkerStatusDAO;
import org.ourgrid.worker.messages.ExecutionControllerMessages;

import br.edu.ufcg.lsd.commune.api.InvokeOnDeploy;
import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;

@Req("REQ084")
public class WorkerExecutionClientReceiver implements WorkerExecutionServiceClient {

	private static final long serialVersionUID = 1L;

	private ServiceManager serviceManager;

	@Req("REQ090")
	@InvokeOnDeploy
	public void init(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}
	
	protected ServiceManager getServiceManager() {
		return serviceManager;
	}
	
	@Req("REQ084")
	public void concurrentExecutionsError() {
		WorkerClient workerClient = getWorkerClient();
		workerClient.sendMessage(new ErrorOcurredMessageHandle(new GridProcessError(GridProcessErrorTypes.CONCURRENT_RUNNING)));

		setExecutionAsFinished(false);
	}

	@Req("REQ087")
	public void executionError(ExecutorException error) {
		WorkerClient workerClient = getWorkerClient();
		workerClient.sendMessage(new ErrorOcurredMessageHandle(
				new GridProcessError(error, GridProcessErrorTypes.EXECUTION_ERROR)));
		
		setExecutionAsFinished(false);
	}

	@Req("REQ087")
	public void executionResult(ExecutorResult result) {
		WorkerClient workerClient = getWorkerClient();
		workerClient.sendMessage(new HereIsGridProcessResultMessageHandle(result));

		if (getWorkerStatusDAO().isAllocatedForRemotePeer()) {
			WorkerController.getInstance().finishWorkAccounting(getServiceManager());
		}

		setExecutionAsFinished(true);
	}
	
	@Req("REQ087")
	public void executionIsRunning(ExecutorHandle handle) {
		ExecutionController.getInstance().executionIsRunning(handle, getServiceManager());
	}
	
	public void allocationError(ExecutorException error) {
		
		getServiceManager().getLog().error(
				ExecutionControllerMessages.getBeginAllocationErrorMessage(error.getMessage()));
		statusChangeAllocatedForBroker();
	}

	public void readyForAllocation() {
		getServiceManager().getLog().debug(
				ExecutionControllerMessages.getBeginAllocationActionIsCompletedMessage());
		statusChangeAllocatedForBroker();
	}

	private void statusChangeAllocatedForBroker() {
		Worker worker = new WorkerReceiver();
		getServiceManager().deploy(WorkerConstants.WORKER, worker);
		
		WorkerStatusDAO statusDAO = getServiceManager().getDAO(WorkerStatusDAO.class);
		
		if (statusDAO.isAllocatedForRemotePeer()) {

			RemoteWorkerManagementClient remotePeerConsumer = statusDAO.getRemotePeerConsumer();
			remotePeerConsumer.statusChangedAllocatedForBroker(worker);
		} else {
			
			WorkerManagementClient masterPeer =
				statusDAO.getMasterPeer();
			masterPeer.statusChangedAllocatedForBroker(worker);
		}
	}

	private void setExecutionAsFinished(boolean success) {
		ExecutionController.getInstance().executionFinish(success, getServiceManager());
	}

	private WorkerClient getWorkerClient() {
		return getWorkerStatusDAO().getConsumer();
	}
	
	private WorkerStatusDAO getWorkerStatusDAO() {
		return getServiceManager().getDAO(WorkerStatusDAO.class);
	}
	
}
